using UnityEngine;

namespace Bomb
{
    public class Bomb : MonoBehaviour
    {
        [SerializeField] private float _radius;
        [SerializeField] private GameObject _explosionEffect;
        [SerializeField] private Managers.StatisticManager _statisticManager;
        private Collider[] _results;
        private Transform _selfTransform;
        private bool _isCollisionEntered;
        private bool _isInvisible;

        private void Start()
        {
            _selfTransform = transform;
        }

        private void OnCollisionEnter()
        {
            if (_isCollisionEntered) return;
            _isCollisionEntered = true;

            Vector3 position = _selfTransform.position;

            Instantiate(
                _explosionEffect,
                position,
                Quaternion.Euler(-90, 0, 0)
            );

            int size = Physics.OverlapSphereNonAlloc(
                position,
                _radius,
                _results);

            for (int i = 0; i < size; i++)
            {
                Collider result = _results[i];
                if (result.TryGetComponent(out Enemy.Enemy enemy))
                {
                    enemy.Kill();
                    _statisticManager.IncreaseDeathCount();
                    return;
                }

                if (result.TryGetComponent(out Player.Player player))
                {
                    player.Kill("взорвал сам себя)");
                }
            }

            if (_isInvisible)
            {
                Destroy(gameObject);
            }
        }

        private void Update()
        {
            if (_isCollisionEntered && _isInvisible)
            {
                Destroy(gameObject);
            }
        }

        private void OnBecameInvisible()
        {
            _isInvisible = true;
        }

        private void OnBecameVisible()
        {
            _isInvisible = false;
        }
    }
}
